package com.syjy.tunnelworker.workassist;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * 用以获取单个线程的线程池以执行单个的线程任务
 *
 * @author: xiuwei
 * @version:
 */
public class SingleThreadPoolExecutorUtil {

	/**
	 * 线程工厂
	 */
	private static final ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("SingleThreadExecutor-1").build();


	/**
	 * 获取执行线程  只允许有一个线程 提交的其他任务也会被拒绝
	 * 线程池可自行销毁
	 *
	 * @return 执行线程池 ExecutorService
	 */
	public static ExecutorService getSingleThreadExecutor() {
		return new ThreadPoolExecutor(0, 1,
				30L, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<>(1), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
	}


	/**
	 * 以单线程池的方式提交线程任务
	 *
	 * @param callable 线程任务
	 * @return 执行的任务
	 */
	public static <T> Future<T> submitBySingleThreadExecutor(Callable<T> callable) {
		return getSingleThreadExecutor().submit(callable);

	}


	/**
	 * 以单线程池的方式执行线程任务
	 *
	 * @param runnable 线程任务
	 */
	public static void executeBySingleThreadExecutor(Runnable runnable) {
		getSingleThreadExecutor().execute(runnable);
	}


	/**
	 * 以单线程池的方式提交线程任务
	 *
	 * @param runnable 线程任务
	 * @return 执行的任务
	 */
	public static Future submitBySingleThreadExecutor(Runnable runnable) {
		return getSingleThreadExecutor().submit(runnable);
	}

	/**
	 * 以单独的线程执行该任务  异常可以外抛
	 *
	 * @param callable 线程执行任务
	 * @return {@link FutureTask}
	 */
	public static FutureTask executeByThread(Callable callable) {
		FutureTask future = new FutureTask(callable);
		new Thread(future).start();
		return future;
	}
}
